#include "xresponse.h"
#include <string.h>
#include <stdio.h>
#include "xcontent.h"
#include "libxsip.h"

XSIPResponse::XSIPResponse()
	: XSIPMessage(XSIPMessage::RESPONSE_MESSAGE)
{
	m_responseCount = 0;
	m_responses = NULL;
}

XSIPResponse::~XSIPResponse()
{
	if (m_responses)
	{
		for (int i = 0; i < m_responseCount; i ++)
		{
			m_responses[i]->setHeader(NULL);
			delete m_responses[i];
		}
		delete []m_responses;
	}
	m_responseCount = 0;
}

void* XSIPResponse::getObject(const char* name) const
{
	if (strcmp(name, "XSIPResponse") == 0)
		return const_cast<XSIPResponse*>(this);
	else
		return XSIPMessage::getObject(name);
}

void XSIPResponse::divide()
{
	XSIPContent *content = getContent();
	int headerSize = getHeader()->getHeaderSize();
	XSIPContent** contents = content->divide(XSIPEngine::getCurrentThreadEngine()->getMTU()-headerSize, &m_responseCount);
	if (m_responseCount > 1)
	{
		m_responses = new XSIPResponse*[m_responseCount];
		for (int i = 0; i < m_responseCount; i ++)
		{
			m_responses[i] = new XSIPResponse();
			m_responses[i]->setHeader(getHeader());
			m_responses[i]->setContent(contents[i]);
		}
	}
	else
		m_responseCount = 0;
}

void XSIPResponse::divide(int step)
{
	XSIPContent *content = getContent();
	XSIPContent** contents = content->divide(step, &m_responseCount);
	if (m_responseCount > 1)
	{
		m_responses = new XSIPResponse*[m_responseCount];
		for (int i = 0; i < m_responseCount; i ++)
		{
			m_responses[i] = new XSIPResponse();
			m_responses[i]->setHeader(getHeader());
			m_responses[i]->setContent(contents[i]);
		}
	}
	else
		m_responseCount = 0;
}

XSIPResponse* XSIPResponse::subResponse(int i)
{
	return m_responses[i];
}

int XSIPResponse::getResponseCount()
{
	return m_responseCount;
}